const express = require("express");
const categoryClassDB = require('../models/category');//分类数据
const contentClassDB = require('../models/content');//文章数据
const multipart = require("connect-multiparty");//数据处理中间件
const multipartMiddleware = multipart();
const router = express.Router();

var config = {};
//处理通用数据
router.use(function (request,response,next) {
    config = {
        userinfo:request.userinfo,
        typelist:[]
    };
    categoryClassDB.find().then(function (data) {
        config.typelist = data;
        next();
    });
});

// 登录主页路由,首页加载
router.get('/',function (request,response,next) {
    // 这里可以用es6的解构赋值 不过node好像没这个语法
    config.limit = 8;
    config.page = Number(request.query.page || 1);
    config.count = 0;
    config.category = request.query.category||'';
    config.content = [];
    config.pages = 0;
    // var cateHead = [];
    var where = {};
    if(config.category){
        where.category = config.category;
    }
    // categoryClassDB.find().then(function (data) {});
    contentClassDB.countDocuments().where(where).then(function (count) {
        // count:总条数
        // pages:总页数
        config.count = count;
        config.pages = Math.ceil(config.count/config.limit);
        config.page = Math.min(config.page,config.pages);
        config.page = Math.max(config.page,1);
        var skip = (config.page - 1)*config.limit;
        // populate方法查找数据表定义的关联字段
        contentClassDB.find().where(where).limit(config.limit).skip(skip).sort({addTime:-1}).populate(['category','user']).then(function (content) {
            config.content = content;
            // console.log(config);
            // console.log(content);
            response.render('main/index',config);
        });
    });


});

router.get('/view',function (request,response,next) {
    // 内容子页get接口
    // url接收的参数用query解析
    const contentId = request.query.contentid || '';
    contentClassDB.findOne({_id:contentId}).populate(['category','user']).then(function (data) {
        config.content = data;
        data.views++;
        data.save();
        // console.log(config);
        response.render('page/content',config);
    })
});


module.exports = router;
